﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _Sql查询结果转List
{
    public class SqlHelper
    {
        public static List<T> GetList<T>(string ConnStr, System.Data.CommandType type, string sql, params SqlParameter[] para) where T : new()
        {
            List<T> list = new List<T>();

            using (SqlConnection conn = new SqlConnection(ConnStr))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandType = type;
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(para);
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            T t = new T();
                            PropertyInfo[] infos = t.GetType().GetProperties();
                            foreach (var info in infos)
                            {
                                info.SetValue(t, sdr[info.Name]);
                            }
                            list.Add(t);
                        }
                    }
                }
            }
            return list;
        }

        

       

    }
}
